package service_config

import (
	"context"
	"fmt"
	"gitee.com/zaper/service-config/constant"
	"gitee.com/zaper/service-config/service/comm_handler"
	"gitee.com/zaper/service-config/service/etcd"
	"gitee.com/zaper/service-config/service/service_register"
	clientv3 "go.etcd.io/etcd/client/v3"
)

func WatchChangeWork() {
	cli := comm_handler.RetryClientEtcd(etcd.GetEtcdClient, 5)
	ctx := context.Background()
	configKey := fmt.Sprintf("/%s", constant.ConfigName)
	watchChan := cli.Watch(ctx, configKey, clientv3.WithPrefix())
	for resp := range watchChan {
		for _, event := range resp.Events {
			// 此处使用异步，为了防止同时存在多次不同类型的变更
			go comm_handler.ChangeHandler(string(event.Kv.Key), "", service_register.GetServiceIdList())
		}
	}
}
